<template>
	<div ref="chartContainer" :style="{ height: height, width: width }"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import T from './echarts-theme-T.js'
echarts.registerTheme('T', T)

const props = defineProps({
	height: {
		type: String,
		default: '100%'
	},
	width: {
		type: String,
		default: '100%'
	},
	nodata: {
		type: Boolean,
		default: false
	},
	option: {
		type: Object,
		default: () => ({})
	}
});

const chartContainer = ref(null)
const myChart = ref(null)

watch(
	() => props.option,
	(newOption) => {
		if (myChart.value) {
			myChart.value.setOption(newOption)
		}
	},
	{ deep: true }
)

onMounted(() => {
	draw()
})

onActivated(() => {
	if (myChart.value) {
		myChart.value.resize()
	}
})

function draw() {
	if (chartContainer.value) {
		// 要添加markRaw，否则echarts会报错 Cannot read properties of undefined (reading ‘type‘)
		myChart.value = markRaw(echarts.init(chartContainer.value, 'T'))
		myChart.value.setOption(props.option)
		window.addEventListener('resize', () => {
			if (myChart.value) {
				myChart.value.resize()
			}
		});

		myChart.value.on("click", (params) => {
			contentByTooltip(params)
		});
	}
}

// 定义事件
const emit = defineEmits(['contentByTooltip']);

function contentByTooltip(params) {
	emit('contentByTooltip', params);
}
</script>